from Lib.SerialPort import *
from Lib.crc16 import *
from Lib.Utils import *
import datetime
import time
import os
import threading
import binascii
import re
class PIDServer(object):

    def __init__(self):
        # self.seria = SerialPort('/dev/serial_1',9600)
        self.seria = SerialPort('/dev/serial_2',9600)
        self.theadPID = None
        self.theadPIDFlag = True
        self.listTem=[]
        self.temp=0
        self.sTem = None
        print('PIDserver初始化成功')

    def open(self):
        print('PIDserver已经启动')
        self.seria.Write(bytes.fromhex('01 06 00 1B 00 00 F9 CD'))
        time.sleep(0.1)
        self.seria.Read()


    def start(self):
        self.theadPIDFlag = True
        self.theadPID=threading.Thread(target=self.pidStableTem,args=(10,10))
        self.theadPID.start()



    def stop(self):
        self.theadPIDFlag = False
        time.sleep(1)


    def close(self):
        self.theadPIDFlag = False
        time.sleep(2)
        self.seria.Write(bytes.fromhex('01 06 00 1B 00 01 38 0D'))
        self.seria.Read()


    def readTem(self):
        #print('PIDserver读取温度值')
        try:
            self.seria.Write(bytes.fromhex('01 03 00 0C 02 04 85 6A'))
            val = str(binascii.b2a_hex(self.seria.Read()).decode())
            if(crc16.calculateCRC(' '.join(['0x'+item  for item in re.findall(r'(.{2})',val[:-4])])).replace(' ','').lower()==val[-4:]):
                d = val[6:10]
                time.sleep(0.3)
                self.temp=int(d, 16) / 100
                return self.temp
            else:
                return None
        except :
            return None

    def setTem(self,temValue):
        #print('PIDserver设置温度值')
        temValue=int(temValue*100)
        hexVal = hex(temValue)[2:].zfill(4)
        sendVal = ('0x' + hexVal[0:2] + ' 0x' + hexVal[2:])
        sendComm = '0x01 0x06 0x00 0x00 ' + sendVal
        sendComm = '01 06 00 00 ' + (hexVal[0:2]).upper() + ' ' +(hexVal[2:]).upper() +' '+ crc16.calculateCRC(sendComm)
        self.seria.Write(bytes.fromhex(sendComm))
        self.seria.Read()

    def pidStableTem(self,stableCount,offsetTem):
        self.listTem = []
        while self.theadPIDFlag:
            try:
                time.sleep(1)
                cTem = self.readTem()
                if(len(self.listTem)>=stableCount):
                    del self.listTem[0]
                if(cTem!=None):
                    self.listTem.append(cTem)
                if(len(self.listTem) < stableCount):
                    self.sTem= None
                else:
                    if(max(self.listTem) - min(self.listTem) <= offsetTem):
                        #self.sTem= float(sum(listTem)) / len(listTem)
                        self.sTem=max(self.listTem)
                    else:
                        self.sTem=None
            except :
                self.sTem= None

    def getStableTem(self):
        return self.sTem
if __name__ == "__main__":
    import PIDServer
    pidServer = PIDServer.PIDServer()
    print(pidServer.readTem())






